package com.cn.api.test;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @program: demo
 * @description:
 * @author: yihanyuan
 * @create: 2019-02-26 13:43
 **/
public class java8lambda {
    List<User> users = Arrays.asList(
            new User(1, "张三", 44),
            new User(2, "李四", 25),
            new User(3, "网二", 50),
            new User(5, "利好", 20),
            new User(6, "利好2", 20)
    );

    @Test
    public void tes1() {
        users.stream()
                .filter((user) -> user.getAge() > 25)
                .forEach(System.out::println);
        System.out.println("-------------------------------");
        List<User> users1 = users
                .stream()
                .filter(user -> user.getAge() > 25 && user.getId() > 2)
                .collect(Collectors.toList());
        users1.stream().forEach(System.out::println);
        System.out.println("-------------------------------");
        users.stream().map(User::getName).forEach(System.out::println);
    }

//    @Test
//    public void test2() {
//        getValue(100, (x) -> System.out::println);
//    }
//
//    public void getValue(Integer i, Consumer<Integer> con) {
//        con.accept(i);
//    }

    @Test
    public void test3() {
        Integer i = getValue(100, (x) -> x * x);
        System.out.println(i);
    }

    public Integer getValue(Integer i, Function<Integer, Integer> fun) {
        return fun.apply(i);
    }

    //    @Test
//    public void test3() {
//        Integer i = getValue(100, (x) -> x * x);
//        System.out.println(i);
//    }
//    public Integer getValue(Integer i, Predicate<Integer> fun) {
//        return fun.apply(i);
//    }
    @Test
    public void test1() {
        //所有满足
        Boolean b = users.stream().allMatch((e) -> e.getAge() == 20);
        System.out.println(b);
        //部分满足
        Boolean b1 = users.stream().anyMatch((e) -> e.getAge() == 20);
        System.out.println(b1);
        Boolean b2 = users.stream().noneMatch((e) -> e.getAge() == 20);
        System.out.println(b2);
        Optional<User> first = users.stream().sorted((e1, e2) -> Double.compare(e1.getAge(), e2.getAge())).findFirst();
        System.out.println(first.get());
        Optional<User> first2 = users.parallelStream().filter(e -> e.getAge() < 30).findAny();
        System.out.println(first2.get());
    }

    /**
     * @return
     * @description 规约求和，第一个参数，初始值，相当于传入的x
     * @author YiHanYuan
     * @params
     * @date 2019/3/29 14:57
     **/
    @Test
    public void test2() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 8, 9);
        Integer reduce = list.stream().reduce(0, (x, y) -> x + y);
        System.out.println(reduce);
//        list.stream().collect(Collectors.averagingDouble());
    }
}
